package com.foreknow.dao.impl;

import com.foreknow.dao.GuestBookDao;
import com.foreknow.mapping.EntityMapping;
import com.foreknow.mapping.MappingFactory;
import com.foreknow.model.GuestBook;
import com.foreknow.util.MysqlPagination;
import com.foreknow.util.Pagination;
import com.foreknow.view.Update;

import java.sql.SQLException;
import java.util.List;

public class GuestBookDaoImpl extends BaseDAO implements GuestBookDao {
    @Override
    public boolean gSave(GuestBook guestBook) throws SQLException {
        String sql = "insert into guestbook(name,phone,email,title,content,createdtime)" +
                " values(?,?,?,?,?,?)";
        int i = jdbcTemplate.update(sql,guestBook.getName(),guestBook.getPhone(),guestBook.getEmail(),
                guestBook.getTitle(),guestBook.getContent(),guestBook.getCreatedTime());
        return i==1;
    }

    @Override
    public List<Object> gQuery() throws SQLException {
        String sql = "select * from guestbook";
        EntityMapping mapping = mappingFactory.getMap(MappingFactory.GUESTBOOK_MAPPING);
        List<Object> guestBooks = jdbcTemplate.query(sql,mapping);
        return guestBooks;
    }

    @Override
    public boolean gDelete(int id) throws SQLException {
        String sql = "delete from guestbook where id=?";
        int i = jdbcTemplate.update(sql, id);
        return i==1;
    }

    @Override
    public boolean gUpdate(GuestBook guestBook, int id) throws SQLException {
        String sql ="update guestbook set name=?,phone=?,email=?,title=?,content=?,createdTime=? where id=?";
        int i = jdbcTemplate.update(sql, guestBook.getName(), guestBook.getPhone(), guestBook.getEmail(),
                guestBook.getTitle(), guestBook.getContent(), guestBook.getCreatedTime(), guestBook.getId());
        return i==1;
    }

    @Override
    public GuestBook gQueryById(int id) throws SQLException {
        String sql = "select * from guestbook where id=?";
        EntityMapping mapping = mappingFactory.getMap(MappingFactory.GUESTBOOK_MAPPING);
        List<Object> list = jdbcTemplate.query(sql, mapping, id);
        GuestBook gb = null;
        if (list.size()==1){
            for (Object guestBook:list){
                gb = (GuestBook) guestBook;
            }
        }

        return gb;
    }

    @Override
    public Pagination getGuestBookByPage(int pageSize, int pageNumber) throws SQLException {
        String sql = "select * from guestbook";
        Pagination pagination = new MysqlPagination(sql,pageSize,pageNumber);
        return pagination;
    }
}
